/**
 * Copyright 2011 Honeywell Federal Manufacturing & Technologies, LLC. This material was produced under U.S. Government
 * contract DE-ACO4-01AL66850, Honeywell Federal Manufacturing & Technologies, LLC, (FM&T) with the U. S. Department of
 * Energy for the operation of the Kansas City Plant . The U.S. Government has rights to use, reproduce, and distribute
 * this software.  NEITHER THE GOVERNMENT NOR Honeywell Federal Manufacturing & Technologies, LLC, MAKES ANY WARRANTY,
 * EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.  If software is modified to produce
 * derivative works, such modified software should be clearly marked, so as not to confuse it with the version available
 * from FM&T.
 *
 * Additionally, this program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License Version 3 published by the Free Software Foundation. Accordingly, this program is distributed in
 * the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this library.
 * If not, see http://www.gnu.org/licenses/.
 */
/**
 * NOTICE:  This computer software was prepared by Honeywell Federal Manufacturing &
 * Technologies, hereinafter the Contractor, under Contract NO. DE-AC04-01AL66850 with 
 * the U.S. Department of Energy (DOE).  All rights in the computer software are 
 * reserved by DOE on behalf of the United States Government and the Contractor as 
 * provided in the Contract.  You are authorized to use this program for Government 
 * purposes but it is not to be released or distributed to the public.  Neither the 
 * Government nor the Contractor makes any warranty, express or implied, or assumes 
 * any liability for the use of this software.  This notice including this sentence 
 * must appear on any copies of this computer software.
 */

package org.braintrain.tapestry.view;

import com.javaforge.tapestry.spring.annotations.InjectSpring;
import org.apache.tapestry.IAsset;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.annotations.Asset;
import org.apache.tapestry.annotations.InjectPage;
import org.braintrain.domain.HomeConfig;
import org.braintrain.domain.Module;
import org.braintrain.domain.Navigation;
import org.braintrain.services.DeltaResourceManager;
import org.braintrain.services.NavigationService;
import org.braintrain.services.search.navigation.StartingNavigationQueryFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Tapestry SkipFinishedChapters page.  Allows the user to skip in past "bookmarked"
 * navigations.
 * 
 * @author John Ericksen
 *
 */

public abstract class SkipFinishedChapters extends BrainTrainSecuredBasePage {
    
    public abstract Long getModuleId();
    public abstract void setModuleId(Long id);
    
    public abstract Navigation getNavigation();
    public abstract void setNavigation(Navigation nav);

    public abstract boolean isModuleFinished();
    public abstract void setModuleFinished(boolean v);
    
    public abstract List<Navigation> getEntryPoints();
    public abstract void setEntryPoints(List<Navigation> entryPoints);
    
    //  Image Assets
    @Asset("/images/undo.gif")
    public abstract IAsset getBackImage();  
    
    @InjectSpring("navigationService")
    public abstract NavigationService getNavigationService();

    @InjectSpring("resourceManager")
    public abstract DeltaResourceManager getResourceManager();
    
    @InjectPage("View")
    public abstract View getViewPage();
    
    private Module currentModule = null;
    
    /**
     * Returns the current module
     * @return
     */
    public Module getModule()
    {
        if(getModuleId() != null && (currentModule == null || currentModule.getId().equals(getModuleId())))
        {
            currentModule = (Module)getGenericService().getById(Module.class, getModuleId());
        }
        return currentModule;
    }

    /**
     * Initilizes this page.  Performs the following:
     * 1. Sets the current module
     * 2. Determines access to this module
     * 3. Finds "bookmarked" pages (EntryPoints)
     * 4. Shows bookmarks to user (if more than the first page is bookmarked)
     * 
     * @param cycle
     * @param id
     */
    public void activate(IRequestCycle cycle, Long id)
    {
          setModuleId(id);
          
          if(!(isDeltaUser() || 
               getModule().getUsers().contains(getBraintrainVisit().getUser())))
          {
              cycle.activate(getNotAuthorizedPage());
          }
          
          Navigation first = (Navigation)getGenericService().findUnique(new StartingNavigationQueryFactory(getModule(), true, false, false));
          
          if(first != null)
          {
              buildModuleEntryPoints();
              
              if(getEntryPoints().size() == 1)
              {
                  ((BrainTrainEditableNavigatablePage)cycle.getPage(first.getType().name()))
                  .activate(cycle, getEntryPoints().get(0).getId(), null);
              }
              else
              {
                  cycle.activate(this);
              }
          }
          else
          {
              cycle.activate("Home");
          }
    }
    
    /**
     * Builds the entry point ("bookmarked") list in a given module
     */
    public void buildModuleEntryPoints()
    {
        List<Navigation> entryPoints = new ArrayList<Navigation>();
        List<Navigation> mainChain = getNavigationService().getMainNavigationChain(getModule());
        entryPoints.clear();
        //add First page
        entryPoints.add(mainChain.get(0));
        
        //add every page after a passed test;
        setModuleFinished(false);
        
        for(Navigation nav: mainChain)
        {
            if(nav.isBookmarkable())
            {
                if(nav.isBookmarked(getBraintrainVisit().getUser()) && nav.getNext() != null)
                {
                    entryPoints.add(nav.getNext());
                }
                else
                {
                    break;
                }
            }
            if(nav.getNext() == null)
            {
                setModuleFinished(true);
            }
        }
        
       setEntryPoints(entryPoints);
        
    }
    
    /**
     * Returns the header as defined in the HomeConfig
     * 
     * @return
     */
    public String getHomeHeader(){
        return getResourceManager().getResourceValue(getHomeConfig().getResource());
    }
    
    
    private HomeConfig config;

    /**
     * Returns the 'HomeConfig'
     * @return
     */
    private HomeConfig getHomeConfig()
    {
        if(config == null)
        {
            List<HomeConfig> configList = getGenericService().getAll(HomeConfig.class);
            
            //really, we shouldnt have more than 1 config in the table
            if(configList.size() > 0)
            {
                config = configList.get(0);
            }
            else
            {
                config = new HomeConfig();
            }
        }
        return config;   
    }
    
}
